'use strict';
var vk; // 全局vk实例
// 涉及的表名
const dbName = "jwc-jslhpjb-obj"; // 教务处-教师量化评价表
//const dbName = "vk-test";
var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
/**
 * 权限注意：访问以下链接查看
 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
 */
var cloudObject = {
	isCloudObject: true, // 标记为云对象模式
	/**
	 * 请求前处理，主要用于调用方法之前进行预处理，一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
	 */
	_before: async function() {
		vk = this.vk; // 将vk定义为全局对象
		// let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
	},
	/**
	 * 请求后处理，主要用于处理本次调用方法的返回结果或者抛出的错误
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
	 */
	_after: async function(options) {
		let {
			err,
			res
		} = options;
		if (err) {
			return; // 如果方法抛出错误，直接return;不处理
		}
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.deletebjcpb 前端调用的url参数地址
	 */
	deletebjcpb: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		await db.collection('jwc-jslhpjb-obj').where({
		  bjid: data.bjid
		}).remove()
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.updatejscpztsz 前端调用的url参数地址
	 */
	updatejscpztsz: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始----------------------------------------------------------- 
		// db.collection('jwc-jslhpjb-obj')
		// .where({sjtxzt:'1'})
		// .update({sjtxzt:'0',sum:0})
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.updateqbjrzt 前端调用的url参数地址
	 */
	updateqbjrzt: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		res.num = db.collection('jwc-xsxxgl-sjb-obj')
		.where({jrzt:'1'})
		.update({jrzt:'0'})

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.getqxjsall 前端调用的url参数地址
	 */
	getqxjsall: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		res.jsall = await vk.baseDao.select({
		  dbName:"jwc-jslhpjb-qx-obj", // 表名
		  getCount:true, // 是否需要同时查询满足条件的记录总数量，默认false
		  getMain:true, // 是否只返回rows数据，默认false
		  pageIndex:1, // 当前第几页
		  pageSize:5000, // 每页条数
		  whereJson:{ // 条件
			 xq: data.xq
		  }
		});

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.getGroupXqxxqx 前端调用的url参数地址
	 */
	getGroupXqxxqx: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		res.xqlist = await vk.baseDao.selects({
			dbName: "jwc-jslhpjb-qx-obj",
			getCount: true,
			getMain: true,
			pageIndex: 1,
			pageSize: -1,
			whereJson: {},
			groupJson: {
				_id: "$xq",
				xq: _.$.first("$xq"),
			},
			sortArr: [],
			lastWhereJson: {}
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.getxqbjall 前端调用的url参数地址
	 */
	getxqbjall: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		res.xqbjall = await vk.baseDao.select({
			dbName: dbName,
			getCount: true,
			getMain: true,
			pageIndex: 1,
			pageSize: 2000,
			whereJson: {
				xq: data.xq,
				bjid: data.bjid
			}
		});

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.getGroupXqxx 前端调用的url参数地址
	 */
	getGroupXqxx: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		res.xqlist = await vk.baseDao.selects({
			dbName: dbName,
			getCount: true,
			getMain: true,
			pageIndex: 1,
			pageSize: -1,
			whereJson: {},
			groupJson: {
				_id: "$xq",
				xq: _.$.first("$xq"),
			},
			sortArr: [],
			lastWhereJson: {}
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.getGroupBjxx 前端调用的url参数地址
	 */
	getGroupBjxx: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		res.bjlist = await vk.baseDao.selects({
			dbName: dbName,
			getCount: true,
			getMain: true,
			pageIndex: 1,
			pageSize: -1,
			whereJson: {
				xq: data.xq
			},
			groupJson: {
				_id: "$bjmc",
				bjmc: _.$.first("$bjmc"),
				bjid: _.$.first("$bjid")
			},
			sortArr: [{ "name": "_add_time", "type": "desc" }],
			lastWhereJson: {}
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 批量审核新媒体任务函数 
	 * @url admin/gsxy/xybx/kh/demoobj.deletePlWxryWzLists 前端调用的url参数地址
	 */
	deletePlWxryWzLists: async function(data) {
		//let { uid } = this.getClientInfo(); // 获取客户端信息
		//let userInfo = await this.getUserInfo(); // 获取当前登录的用户信息s
		//console.log("请求参数", data);

		// 业务逻辑开始-----------------------------------------------------------
		let res = {
			code: 0,
			msg: ''
		};
		let {
			_ids
		} = data;
		// 参数非空检测
		if (vk.pubfn.isNullOne(_ids)) {
			return {
				code: -1,
				msg: '参数错误'
			};
		}

		//1.批量删除
		// 返回被删除的记录条数
		res.num = await vk.baseDao.del({
			dbName: dbName,
			whereJson: {
				_id: _.in(_ids)
			}
		});

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/xybx/kh/demoobj.deleteWxryWzListOne 前端调用的url参数地址
	 */
	deleteWxryWzListOne: async function(data) {
		
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		//console.log("请求参数", data);
		// 业务逻辑开始-----------------------------------------------------------
		// 这里id不传默认设置成"___" 是为了防止因未传_id导致误删所有数据.
		let {
			_id
		} = data;
		if (vk.pubfn.isNull(_id)) {
			return {
				code: -1,
				msg: 'id不能为空'
			};
		}
		res.num = await vk.baseDao.deleteById({
			dbName,
			id: _id
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.updateWxryWzListOne 前端调用的url参数地址
	 */
	updateWxryWzListOne: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		let updateId = data._id
		Reflect.deleteProperty(data, '_id')
		await vk.baseDao.updateById({
			dbName: dbName,
			id: updateId,
			dataJson: {
				...data
			}
		});
		res.jslhpjblist = await vk.baseDao.select({
		  dbName:dbName,
		  getCount:true,
		  getMain:true,
		  pageIndex:1,
		  pageSize:-1,
		  whereJson:{
		    xq:data.xq,
			bjmc:data.bjmc
		  },

		});
		let jslhpjblistlet = res.jslhpjblist//所有学生
		
		res.fhsj = vk.myfn.uniqueArrayjs(jslhpjblistlet)
		let fhsj = res.fhsj//所有教师
		for (let i = 0; i < fhsj.length; i++) {
			fhsj[i].ystemp =0
			for (let a = 0; a < jslhpjblistlet.length; a++) {
				if(fhsj[i].jsbh == jslhpjblistlet[a].jsbh && jslhpjblistlet[a].sum >= 85){
					fhsj[i].ystemp +=1
				}
			}
		}
		//获取学生人数
		for (let i = 0; i < fhsj.length; i++) {
			fhsj[i].xsrs =0
			for (let a = 0; a < jslhpjblistlet.length; a++) {
				if(fhsj[i].jsbh == jslhpjblistlet[a].jsbh){
					fhsj[i].xsrs +=1
				}
			}
		}
		//获取优率
		for (let i = 0; i < fhsj.length; i++) {
			fhsj[i].scores = 0
			for (let a = 0; a < jslhpjblistlet.length; a++) {
				if(fhsj[i].jsbh == jslhpjblistlet[a].jsbh){
					fhsj[i].scores = (fhsj[i].ystemp/fhsj[i].xsrs)
					//fhsj[i].scores =parseFloat((fhsj[i].ystemp/fhsj[i].xsrs).toFixed(5))
				}
			}
		}
		res.ylfs = vk.myfn.aaaa1(fhsj)

		res.ylpms = 0
		for (let i = 0; i < res.ylfs.length; i++) {
			if(fhsj[i].jsbh == res.ylfs[i].jsbh){
				//fhsj[i].ylpms = parseFloat((res.ylfs[i].gys/res.ylfs.length).toFixed(5))
				fhsj[i].ylpms = (res.ylfs[i].gys/res.ylfs.length)
				fhsj[i].ystemp =res.ylfs[i].ystemp
				fhsj[i].cjsr =res.ylfs[i].cjsr
				fhsj[i].gys =res.ylfs[i].gys
			}
		}

		let newArraya = fhsj.map(obj => {  
			delete obj.xm
			delete obj.zjhm
			delete obj._add_time
			delete obj._add_time_str
			delete obj._id
			delete obj.sum
		    return obj
		});  
		res.newArraya =newArraya

		let infoddd;
		for (let i = 0; i < newArraya.length; i++) {
	
			let infoddd = await vk.baseDao.findByWhereJson({
			  dbName:"jwc-jslhpjb-qx-obj",
			  whereJson:{
			    bjid: newArraya[i].bjid,
				jsbh: newArraya[i].jsbh,
				xq: newArraya[i].xq
			  }
			});

			if(infoddd && infoddd._id){
				let newInfo = await vk.baseDao.updateById({
				  dbName:"jwc-jslhpjb-qx-obj",
				  id:infoddd._id,
				  dataJson:{
					bjid: newArraya[i].bjid,
					bjmc: newArraya[i].bjmc,
					cjsr: newArraya[i].cjsr,
					count: newArraya[i].count,
					gys: newArraya[i].gys,
					jsbh: newArraya[i].jsbh,
					jsxm: newArraya[i].jsxm,
					pmcj: newArraya[i].pmcj,
					scores: newArraya[i].scores,
					xq: newArraya[i].xq,
					xsrs: newArraya[i].xsrs,
					ylpms: newArraya[i].ylpms,
					ystemp: newArraya[i].ystemp
				  }
				});
			}else{
				await vk.baseDao.add({
				  dbName:"jwc-jslhpjb-qx-obj",
				  dataJson:{
				    bjid: newArraya[i].bjid,
				    bjmc: newArraya[i].bjmc,
				    cjsr: newArraya[i].cjsr,
				    count: newArraya[i].count,
				    gys: newArraya[i].gys,
				    jsbh: newArraya[i].jsbh,
				    jsxm: newArraya[i].jsxm,
				    pmcj: newArraya[i].pmcj,
				    scores: newArraya[i].scores,
				    xq: newArraya[i].xq,
				    xsrs: newArraya[i].xsrs,
				    ylpms: newArraya[i].ylpms,
				    ystemp: newArraya[i].ystemp
				  }
				});
			}


		}

		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/jwc-kqgl/jwc-jslhpjb-obj.addWxryWzListOne 前端调用的url参数地址
	 */
	addWxryWzListOne: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		let {
			kq,
			bjid
		} = data
		// 业务逻辑开始-----------------------------------------------------------
		const bjinfo={
			_id:bjid
		}
		
		const bjjjjinfo = await vk.baseDao.findById({
		  dbName:"jwc-bjgl",
		  id:bjid,
			fieldJson:{
			 bjmc: true
			}
		});
		
		//1.获取在校学生数据
		const zxxs = await vk.baseDao.select({
			dbName: "jwc-xsxxgl-obj", // 表名 ...
			getCount: true,
			getMain: true,
			pageIndex: 1,
			pageSize: -1,
			whereJson: {
				bjinfo:bjinfo
			}
		});
		//2.获取分配班级的教师 
		const rkjs = await vk.baseDao.select({
			dbName: "jwc-bjjsgl-obj", // 表名 ...
			getCount: true,
			getMain: true,
			pageIndex: 1,
			pageSize: -1,
			whereJson: {
				bjinfo:bjinfo
			}
		});
		//3.获取已经存在的数据
		const sjjh = await vk.baseDao.selects({
			dbName: dbName,// jwc-jslhpjb-obj
			getCount: true,
			getMain: true,
			pageIndex: 1,
			pageSize: -1,
			// 主表where条件
			whereJson: {
				xq: kq,
				bjid:bjid
			}
		});

		let jslhpjsj = []
		for (var i = 0; i < zxxs.length; i++) {
			for (var x = 0; x < rkjs.length; x++) {
				if (zxxs[i].bjinfo._id == rkjs[x].bjid) {
					let jsobj = {
						xq: data.kq,
						zjhm: zxxs[i].sfzh,
						xm: zxxs[i].xm,
						xh: zxxs[i].xh,
						bjmc: bjjjjinfo.bjmc,
						bjid: rkjs[x].bjid,
						jsxm: rkjs[x].rkjsinfo.nickname,
						jsbh: rkjs[x].rkjsinfo.jsbh,
						sum: 0,
						sjtxzt: '0'
					}
					jslhpjsj.push(jsobj)
				}
			}
		}
		res.jslhpjsj = jslhpjsj
		res.sjjh = sjjh


		const result = jslhpjsj.filter(item => !sjjh.some(obj => item.xq == obj.xq && item.zjhm == obj.zjhm &&
			item.jsbh == obj.jsbh && item.bjid == obj.bjid));
		res.result = result

		if (result.length == 0) {
			return res = {
				code: -1,
				msg: '没有需要增加的数据'
			};
		}

		res.fhsj = await vk.baseDao.adds({
			dbName: dbName, // 表名
			dataJson: result
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/gsxy/xybx/kh/demoobj.getWxryWzListList 前端调用的url参数地址 
	 */
	getWxryWzListList: async function(data) {
		//let { uid, filterResponse, originalParam } = this.getClientInfo(); // 获取客户端信息
		let res = {
			code: 0,
			msg: ''
		};
		// 业务逻辑开始-----------------------------------------------------------
		//console.log("请求参数", data);
		res = await vk.baseDao.getTableData({
			dbName,
			data,
			sortArr:[{ name:"_add_time", type:"desc" }],
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
};

module.exports = cloudObject;